package com.cloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.cloud.entity.CommonResult;
import com.cloud.entity.Payment;
import com.cloud.service.GetOrderByFeign;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.regex.Pattern;

@RestController
@RefreshScope
public class RequestController {

    @Resource
    public RestTemplate restTemplate;

    @Value("${config.version}")
    public String version;

    @Value("${payment.url}")
    String url;


    @Resource
    GetOrderByFeign getOrderByFeign;

    /**
     * block为配置异常调用方法 会受到降级中的异常数和异常比例限制影响 主要是针对于配置上的限制进行流量降级
     * fallback为程序异常调用方法出现的异常进行对应的处理
     * 如果block和fallback条件同时触发，则执行block配置方法
     * @param id
     * @return
     */
    @RequestMapping(value = "payment/get/{id}")
    @SentinelResource(value = "payment/get",
            blockHandlerClass = SentinelHandler.class,
            blockHandler = "sentinelExceptionHandlerForGetOrder",
            fallbackClass = SentinelFallBackHandler.class,
            fallback = "fallBackHandlerOnException"
    )
    public CommonResult<Payment> getOrder(@PathVariable String id) throws Exception {
        if(StringUtils.isBlank(id) ){
            throw new Exception("id错误");
        }
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        boolean re = pattern.matcher(id).matches();
        if(!re){
            throw new Exception("id异常");
        }
        return getOrderByFeign.getOrder(id);
    }



    @RequestMapping(value = "get/version")
    /**
     * 自定义sentinel类与执行方法
     */
    @SentinelResource(value = "version",blockHandlerClass = SentinelHandler.class,blockHandler = "sentinelExceptionHandlerForVersion")
    public String getVersion(){
        System.out.println(version);
        return version;
    }

    public CommonResult<Payment> exceptionHandler(String id, BlockException e){
        return new CommonResult<>(2001, "this is exception"+e.getMessage());
    }


//    public static CommonResult<Payment> fallBackHandlerOnException(@PathVariable String id,Throwable e){
//        return new CommonResult<>(2001, e.getMessage());
//    }
}
